import { watchEffect, ref } from 'vue'
import type { Ref, ComputedRef } from 'vue'
import { cloneDeep, debounce } from 'lodash'

type QueryFuncType<T, R> = (params: T) => Promise<R>
type OptionsType = {
    rowMerge:boolean,
    colMerge:boolean
}
/**
 *
 * @param TableData        表格数据
 * @param QueryFormParams  查询表单参数
 * @param QueryCbFunc        查询解析函数
 * @param PageSize         每页显示条数
 * @param PageNum           当前页码
 */

export default function useTable<T, Q>(
    TableData: Ref<T>,
    QueryFormParams: ComputedRef<Q>,
    QueryCbFunc: QueryFuncType<Q & { pageSize: number; pageNum: number }, T>,
    PageSize: Ref<number>,
    PageNum: Ref<number>,
    Options:OptionsType
):[Ref<T>, Ref<boolean>] {
    let loading = ref(false)
    let debounceQueryFunc = debounce(() => {
      loading.value=true
        let params = {
            ...cloneDeep(QueryFormParams.value),
            pageSize: PageSize.value,
            pageNum: PageNum.value
        }
        QueryCbFunc(params).then(data=>{
            loading.value=false
            TableData.value = data
        })
    }, 500)

    watchEffect(debounceQueryFunc)

    return [TableData, loading]
}
